<template>
    <view class="container">
		<!-- 顶部安全区域占位 -->
		<view class="navbar" :style="{ paddingTop: safeAreaInsets.top-10 + 'px' }"></view>
		<!-- 房间成员（折叠面板） -->
		<view v-if="isLoading">
			<uni-collapse>
				<uni-collapse-item title="房间成员" :open="true" :show-arrow="false" :title-border="'none'">
					<view>正在加载房间成员信息...</view>
				</uni-collapse-item>
			</uni-collapse>
		        
		</view>
       <view v-else>
			<uni-collapse>
				<uni-collapse-item title="房间成员" :open="true" :show-arrow="false" :title-border="'none'">
					<view class="content fade-in">
						<view class="user" v-for="(member, userId) in members" :key="userId">
						    <image :src="member.avatar" class="avatar"></image>
						    <text class="username">{{ member.nickname || member.name }}</text>
						</view>
					</view>
				</uni-collapse-item>
			</uni-collapse>
		</view>
		<!-- 对局记录（消息卡片） -->
		<!-- 这里感觉应该是在页面初始化去后端对局记录中获取数据，根据数据条数动态生成卡片 -->
		<view class="custom-card" v-for="(record, index) in history" :key="index">
		    <view class="card-time">
		        <text class="card-text">{{ record.time }} · 第{{ index + 1 }}局</text>
		    </view>
		    <view class="card-score">
		        <view class="card-item" v-for="(score, userId) in record.scores" :key="userId">
		            <!-- <image :src="getPlayerAvatar(userId)" class="avatar"></image> -->
					<image src="https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/unicloudlogo.png" ></image>
		            <text class="card-text">{{ score }}</text>
		        </view>
		    </view>
		</view>
		
		<!-- 底部功能区域 -->
		<view class="foot fade-in">
		        <button class="footbutton-left" @click="settleRound">
		            <text> 结算本局 </text>
		        </button>
					
		        <image class="share" src="@/static/user.png"></image>
					
		        <button class="footbutton-right" @click="leaveRoom">
					离开房间
				</button>
		</view>
    </view>
</template>

<script setup>
// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
import { useSocketStore } from '@/stores/socketStore';
import { ref, onMounted, onUnmounted, watch} from 'vue';
import { onLoad,onShow} from '@dcloudio/uni-app';
// 房间信息
const roomId = ref('');

const members = ref({});

const history = ref([
    {	
		time: '10:00:00',
        scores: {'user1': 10,'user2': 20,'user3': 30,'user4': 40}
    },
    {
        time: '2025-02-17 11:00:00',
        scores: {'user1': 15,'user2': 25,'user3': 35,'user4': 45}
    }
]);
// 获取 Socket Store
const socketStore = useSocketStore();
//折叠面板信息刷新监听
const isLoading = ref(true);
watch(members, () => {
    isLoading.value = false;
}, { deep: true });



// 监听用户加入事件（使用 Store 提供的 on 方法）
// socketStore.on('user_joined', (data) => {
//   const userId = data.user_id;
//   if (!members.value[userId]) {
//     members.value = { 
//       ...members.value,
//       [userId]: data 
//     };
//   }
// });
// 封装事件处理函数（便于卸载时引用）
const handleUserJoined = (data) => {
  const userId = data.user_id;
  members.value = { 
    ...members.value, 
    [userId]: data 
  };
};
socketStore.on('user_joined', handleUserJoined);









// 折叠面板数据初始化
const refreshRoomData = () => {
  if (!roomId.value) return;
  isLoading.value = true;
  socket.value.emit('init_room', { room_id: roomId.value });
};







onMounted(() => {
	const options = getCurrentPages()[getCurrentPages().length - 1].options;
    roomId.value = options.room_id; // 从 URL 参数中获取 roomId
	
    if (!roomId.value) return;
    // 初始化 Socket 连接（复用或创建）
    const socket = socketStore.initSocket(roomId.value);
	refreshRoomData();

	
	//*******************（房间专属事件）***************************
	// 1 监听用户加入事件
	const handleUserJoined = (data) => {
		members.value = { ...members.value, [data.user_id]: data };
	};
	socketStore.on('user_joined', handleUserJoined);
	
	// 2 监听用户离开事件
	const handleUserLeft = (data) => {
	const newMembers = { ...members.value };
	delete newMembers[data.user_id];
		members.value = newMembers;
	};
	socketStore.on('user_left', handleUserLeft);
	

	// 监听自定义事件——房间用户信息更新
	socket.value.on('room_user_init', (data) => {
		// 这里更新完newuserlist之后是否应该通知同一房间内所有用户？
	    console.log('房间初始化后members:', data);
		members.value = { ...data }; // 用展开运算符触发响应式
		joinRoom();
	});
	// 监听自定义事件——用户加入
	socket.value.on('user_joined', (data) => {
		const userId = data.user_id; // 明确userId作为键
		if (!members.value[userId]) {
			// 正确触发响应式更新的写法
			members.value = {
				...members.value,
				[userId]: data
			};
			console.log('新增用户:', data.user_id);
		} else {
			console.log('用户已存在:', data.user_id);
			// 可选：如果需要更新现有用户数据
			// members.value = { ...members.value };
		}
	});
	// 监听自定义事件——用户离开
	socket.value.on('user_left', (data) => {
		const userId = data.user_id;
		// 先复制原对象，再删除属性，最后重新赋值
		const newMembers = { ...members.value };
		delete newMembers[userId]; // 删除用户
		members.value = newMembers; // 触发响应式更新
	});	
	
	
	// 页面卸载时解绑事件（关键：避免内存泄漏）
	onUnmounted(() => {
	    socketStore.off('user_joined', handleUserJoined);
	    socketStore.off('user_left', handleUserLeft);
	});
});

// 页面显示时执行（从其他页面返回时）
onShow(() => {
  refreshRoomData();
});

// 加入房间—————— 加入房间是否要鉴权？
const joinRoom = () => {
	const user = JSON.parse(uni.getStorageSync('user'));//读取storage中的JSON字符串并解析为JSON对象
	const userid = user.userinfo?.userid;//访问userid
	const isUserInRoom = String(userid) in members.value;
	if (isUserInRoom) {
	    console.log('用户已经在房间中，无需重复加入');
	    return;
	}
    socket.value.emit('jinfangjian', { room_id: roomId.value, user_id: userid });
};

// 离开房间
const leaveRoom = () => {
	const user = JSON.parse(uni.getStorageSync('user'));//读取storage中的JSON字符串并解析为JSON对象
	const userid = user.userinfo?.userid;//访问userid
	console.log(userid)
    socket.value.emit('leave_room', { room_id: roomId.value, user_id: userid });
    uni.navigateBack();
}; 

// 结算本局
const settleRound = async () => {
  try {
    // 1. 获取房间最新数据（包含current_game） ---感觉这两个请求可以合在一起  没必要单独为了一个roundid发送一次请求
    const res = await uni.request({
      url: `http://172.16.24.120:5000/mysqlroom/get_room_info/${roomId.value}`,
      method: 'GET'
    });

    uni.navigateTo({
      url: `/pages/room/roundpay?roomId=${roomId.value}&roundNumber=${res.data.current_game}`
    });
	// socket.value.emit('update_score', {
	//     room_id: roomId.value,
	//     scores: scores
	// });
    
  } catch (err) {
    uni.showToast({
      title: '获取房间信息失败',
      icon: 'none'
    });
  }
}


// 离开房间时关闭连接
const leaveRoom = () => {
  socketStore.closeSocket(); // 关闭全局连接
  uni.navigateBack();
};




 


</script>

<style>
	.navbar{
	/* 		安全距离background-size: cover;	
			position:relative; display:flex;
			flex-direction:column; */
			/* padding-top:20px; */
			/* z-index: 3; */
			/* background-color: green; */
		}
	.container {
		display: flex;
		flex-direction: column;
		width: 100%;
		height: 100%;
	}

	/* 折叠面板 */
	.content {
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-around;
	}

	.avatar {
		width: 50px;
		height: 50px;
		border-radius: 50%;
	}

	.user {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 13px;
	}

	/* 消息卡片 */
	.custom-card {
	    display: flex;
	    flex-direction: column; /* 改为竖直方向排列 */
	    justify-content: space-around;
	    align-items: center;
	    padding: 20px; /* 增加内边距 */
	    margin: 20px;/* 增加外边距，与边界保持合适距离 */
	    /* border: 1px solid #ccc; */
	    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
	    background-color: #fff;
	    border-radius: 8px;
	}
	.card-time {
	    margin-bottom: 20px; /* 在时间区下方添加间距 */
	}
	.card-score {
	    display: flex;
	    flex-direction: row; /* 使card-item水平排列 */
	    justify-content: space-around; /* 均匀分布子元素 */
	    /* align-items: center; */
	}
	.card-item {
	    display: flex;
	    flex-direction: column;
	    align-items: center;
	    margin: 0 26px;
	}	
	.card-text {
	    font-size: 14px;
	    color: #a0a6a7;
		text-align: center;
	}
	.card-item image {
	    width: 42px;
	    height: 42px;
	    margin-bottom: 5px;
	    border-radius: 10%;
	}
/* 整体底部容器样式 */
.foot {
    position: fixed;
    bottom: 20px; /* 距离底部20px，可以根据需求调整 */
    left: 0;
    right: 0;
    display: flex;
    justify-content: space-around;
    align-items: center;
    /* background-color: #f0f0f0; 
    border-radius: 10px; 
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.2); 
    padding: 10px 0; */
}

/* 左边按钮样式 */
.footbutton-left {
    background-color: #8b8a84;
    color: white;
    border: none;
    border-radius: 50px;
    cursor: pointer;
	transition: background-color 0.3s ease; /* 过渡效果 */
	width: 125px; 
	height: 60px; 
	font-size: 18px;
	display: flex;
	justify-content: center;
	align-items: center;
}



/* 右边按钮样式 */
.footbutton-right {
    background-color: #41403b;
    color: white;
    border: none;
    border-radius: 50px;
    cursor: pointer;
	transition: background-color 0.3s ease; /* 过渡效果 */
    width: 125px; 
    height: 60px; 
    font-size: 18px;
    display: flex;
    justify-content: center;
    align-items: center;
}
/* 分享图标样式 */
.share {
    width: 60px; /* 图标宽度 */
    height: 60px; /* 图标高度 */
    object-fit: contain; /* 保持图片比例 */
}
.share:hover {
    transform: scale(1.3); /* 鼠标悬停时放大 */
}

/* 鼠标悬停时改变背景色 */
.footbutton-left:hover,
.footbutton-right:hover {
    background-color: #0056b3; 
}
/* 淡入动画 */
.fade-in {
    animation: fadeIn 0.3s ease-in-out;
}
@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(10px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}
</style>